import { ref } from "vue";
import { useRoute } from "vue-router";
import {
  type ModuleField,
  type ModuleTable,
  getModuleTableDetails,
  updateModuleTable
} from "@/views/domain/devtools/api/moduleTable";
import type { PlusColumn } from "plus-pro-components";

export type FieldItem = ModuleField & {
  id?: number;
};

const dataType = [
  { label: "字符串", goType: "string", tsType: "string" },
  { label: "日期", goType: "time.Time", tsType: "number" },
  { label: "Int", goType: "int", tsType: "number" },
  { label: "Float", goType: "float32", tsType: "number" },
  { label: "Bool", goType: "bool", tsType: "boolean" },
  { label: "Json", goType: "*vo.JSONType[any]", tsType: "any" }
];

export function useDevtoolsGen() {
  const route = useRoute();
  const details = ref<ModuleTable>();
  const tableData = ref<FieldItem[]>([]);

  function autoFillFieldsContent() {
    tableData.value.forEach(field => {
      if (field.fieldName && field.jsonName === "") {
        field.jsonName = field.fieldName;
      }
      if (field.goType && field.tsType === "") {
        field.tsType = dataType.find(
          item => item.goType === field.goType
        )?.tsType;
      }
    });
  }
  const tableColumns: PlusColumn[] = [
    {
      label: "域",
      prop: "domain",
      fieldProps: {
        disabled: true
      }
    },
    {
      label: "类名",
      prop: "className",
      fieldProps: {
        disabled: true
      }
    },
    {
      label: "数据表",
      prop: "dbTable"
    },
    {
      label: "备注",
      prop: "comment"
    },
    {
      label: "域路由",
      prop: "domainRoute",
      fieldSlots: {
        // prepend: () => <span>{`/api/v1/`}</span>,
        // append: () => <span>{`/${details.value?.classRoute || ""}/*`}</span>
      }
    },
    {
      label: "表路由",
      prop: "classRoute",
      fieldSlots: {
        // prepend: () => (
        //   <span>{`/api/v1/${details.value.domainRoute || "DOMAIN_ROUTE"}/`}</span>
        // ),
        // append: () => <span>{"/*"}</span>
      }
    },
    {
      label: "权限检查",
      prop: "auth",
      renderField(value, onChange) {
        return (
          <el-switch
            v-model={value}
            inline-prompt
            active-value={1}
            inactive-value={-1}
            onChange={onChange}
          />
        );
      }
    }
  ];

  const fieldColumns: PlusColumn[] = [
    {
      label: "字段名称",
      prop: "fieldName",
      width: 200,
      fixed: "left",
      cellRenderer: ({ row }) => <el-input v-model={row.fieldName} />
    },
    {
      label: "主键",
      prop: "isPk",
      width: 80,
      valueType: "switch",
      cellRenderer: ({ row }) => (
        <el-switch
          v-model={row.isPk}
          inline-prompt
          active-value={1}
          inactive-value={-1}
        />
      )
    },
    {
      label: "索引",
      prop: "isIndex",
      width: 80,
      valueType: "switch",
      cellRenderer: ({ row }) => (
        <el-switch
          v-model={row.isIndex}
          inline-prompt
          active-value={1}
          inactive-value={-1}
        />
      )
    },
    {
      label: "唯一",
      prop: "isUnique",
      width: 80,
      valueType: "switch",
      cellRenderer: ({ row }) => (
        <el-switch
          v-model={row.isUnique}
          inline-prompt
          active-value={1}
          inactive-value={-1}
        />
      )
    },
    {
      label: "Json名称",
      prop: "jsonName",
      width: 150,
      cellRenderer: ({ row }) => <el-input v-model={row.jsonName} />
    },
    {
      label: "可空",
      prop: "nullAble",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-switch
          v-model={row.nullAble}
          inline-prompt
          active-value={1}
          inactive-value={-1}
        />
      )
    },
    {
      label: "Go类型",
      prop: "goType",
      width: 150,
      cellRenderer: ({ row }) => (
        <el-select v-model={row.goType}>
          {dataType.map(item => {
            return (
              <el-option
                key={item.goType}
                label={item.label}
                value={item.goType}
              />
            );
          })}
        </el-select>
      )
    },
    {
      label: "Ts类型",
      prop: "tsType",
      width: 150,
      cellRenderer: ({ row }) => (
        <el-select v-model={row.tsType}>
          {dataType.map(item => {
            return (
              <el-option
                key={item.label}
                label={item.label}
                value={item.tsType}
              />
            );
          })}
        </el-select>
      )
    },
    {
      label: "快速搜索",
      prop: "quickSearch",
      width: 150,
      cellRenderer: ({ row }) => <el-input v-model={row.quickSearch.match} />
    },
    {
      label: "acl校验",
      prop: "validation",
      width: 150
    },
    {
      label: "注释",
      prop: "comment",
      width: 150,
      cellRenderer: ({ row }) => <el-input v-model={row.comment} />
    },
    {
      label: "操作",
      prop: "operation",
      slot: "operation",
      fixed: "right"
    }
  ];

  const reloadTable = async () => {
    const { domain, className } = route.query;
    const { data } = await getModuleTableDetails({
      domain: domain as string,
      className: className as string
    });

    details.value = data;
    tableData.value = data.fields || [];
  };

  const saveTable = (moduleTable: any) => {
    updateModuleTable({
      ...moduleTable,
      fields: tableData.value
    });
  };

  return {
    details,
    reloadTable,
    tableColumns,
    fieldColumns,
    tableData,
    saveTable,
    autoFillFieldsContent: () => autoFillFieldsContent(),
    deleteRow(data) {
      tableData.value = tableData.value.filter(
        item => item.fieldName !== data.fieldName
      );
    },
    addRow() {
      tableData.value.push({
        fieldName: "",
        isPk: -1,
        isIndex: -1,
        isUnique: -1,
        jsonName: "",
        goType: "",
        tsType: "",
        quickSearch: {
          match: ""
        },
        validation: {
          required: false
        },
        comment: "",
        domain: "",
        className: "",
        inSearch: -1,
        inCreate: -1,
        inEdit: -1
      });
    }
  };
}

export function useGenConfig() {
  const genOptionColumn: PlusColumn[] = [
    { label: "后端-acl", prop: "backAcl", valueType: "switch" },
    { label: "后端-Api", prop: "backApi", valueType: "switch" },
    { label: "后端-Entity", prop: "backEntity", valueType: "switch" },
    { label: "后端-HttpClient", prop: "backHttpClient", valueType: "switch" },
    { label: "后端-HttpRouter", prop: "backHttpRouter", valueType: "switch" },
    { label: "后端-HttpTest", prop: "backHttpTest", valueType: "switch" },
    { label: "后端-Repo", prop: "backRepo", valueType: "switch" },
    { label: "后端-Service", prop: "backService", valueType: "switch" },
    { label: "前端-Api", prop: "frontApi", valueType: "switch" },
    { label: "前端-View", prop: "frontView", valueType: "switch" },
    {
      label: "前端-ViewProvider",
      prop: "frontViewProvider",
      valueType: "switch"
    }
  ];
  return {
    genOptionColumn
  };
}
